package com.grace.cms.general.service.page;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;

import com.grace.common.config.GraceConfig;
import com.grace.common.enums.GraceServerRoot;
import com.grace.cms.common.enums.ArticleTypeEnums;
import com.grace.cms.common.enums.CategoryNodeTypeEnums;
import com.grace.cms.common.enums.properties.OlyWebConfigProperties;
import com.grace.cms.common.model.support.PageData;
import com.grace.cms.general.cache.GeneralThemeCacheService;
import com.grace.cms.general.controller.CommonController;
import com.grace.cms.general.taglib.ArticleTag;
import com.grace.cms.query.model.param.ArticleSearchParam;
import com.grace.cms.query.model.vo.WebArticleVo;

@Service
public class WebPageService extends CommonController {
    private static final Logger log = LoggerFactory.getLogger(WebPageService.class);
    @Autowired
    private ArticleTag articleService;
    @Autowired
    private GeneralThemeCacheService themeService;

    /**
     * 主页
     *
     * @param themeName 主题名称
     * @param mp
     * @return
     */
    public String index(String themeName, ModelMap mp) {
        mp.put("column", getCmsColumn(themeName, OlyWebConfigProperties.PAGE_INDEX));
        try {
            Integer.parseInt(mp.get("pageNum").toString());
        } catch (Exception e) {
            mp.put("pageNum", 1);
        }
        return getPrefix(themeName, "/pages/web/index", mp);
    }

    /**
     * 文章列表
     * 
     * @param themeName 主题名字
     * @param type      文章类型
     * @param mp
     * @param parm      查询参数
     * @return
     */
    public String listWebArticle(String themeName, ArticleTypeEnums type, ModelMap mp, ArticleSearchParam parm) {
        mp.put("column", getCmsColumn(themeName, OlyWebConfigProperties.PAGE_ARTICLES));
        parm.setSupportCategoryId(
                themeService.selectCmsTheme(GraceConfig.getOnlyCode(), themeName).getMainCategoryId());
        parm.setArticleTypeEnum(type);
        List<WebArticleVo> list = new ArrayList<>();
        startPage();
        //list = articleService.listWebArticles(parm);
        mp.put("articleType", type.name());
        mp.put("pageArticle", PageData.getData(list, 200));
        return getPrefix(themeName, "/pages/web/articles", mp);
    }

    /**
     * 文章页
     *
     * @param themeName
     * @param articleId
     * @param mp
     * @return
     */
    public String selectArticleById(String themeName, Long articleId, ModelMap mp) {
        mp.put("articleId", articleId);
        return getPrefix(themeName, "/pages/web/article", mp);
    }

    /**
     * 获取主题支持的分类
     *
     * @param themeName
     * @param nodeTypeEnums
     * @param mp
     * @return
     */
    public String listCmsCategory(String themeName, CategoryNodeTypeEnums nodeTypeEnums,Long categoryId, ModelMap mp) {
        if(nodeTypeEnums == null)  {
           nodeTypeEnums=CategoryNodeTypeEnums.DEFAULT;
         }
        mp.put("column", selectCmsColumnByIdItem(themeName,
                OlyWebConfigProperties.PAGE_CATEGORY_PREFIX.getValue() + nodeTypeEnums.name().toLowerCase()));
        mp.put("nodeType", nodeTypeEnums.name());
        mp.put("categoryId", categoryId);
        return getPrefix(themeName, "/pages/web/categories", mp);
    }

    /**
     * 依据分类ID获取文章
     *
     * @param themeName
     * @param catId
     * @param mp
     * @return
     */
    public String selectCmsCategoryById(String themeName, Long categoryId, ModelMap mp) {
        mp.put("categoryId", categoryId);
        return getPrefix(themeName, "/pages/web/category", mp);
    }

    /**
     * 获取链接列表
     *
     * @param themeName
     * @param mp
     * @return
     */
    public String links(String themeName, ModelMap mp) {
        mp.put("column", getCmsColumn(themeName, OlyWebConfigProperties.PAGE_LINKS));
        return getPrefix(themeName, "/pages/web/links", mp);
    }

    public String query(String themeName, ModelMap mp) {
        mp.put("column", getCmsColumn(themeName, OlyWebConfigProperties.PAGE_QUERY));
        return getPrefix(themeName, "/pages/web/query", mp);
    }

    /**
     * 获取链接
     *
     * @param themeName
     * @param linkId
     * @param mp
     * @return
     */
    public String link(String themeName, Long linkId, ModelMap mp) {
        mp.put("linkId", linkId);
        return getPrefix(themeName, "/pages/web/link", mp);
    }

    /**
     * 介绍页面
     *
     * @param themeName
     * @param mp
     * @return
     */
    public String about(String themeName, ModelMap mp) {
        mp.put("column", getCmsColumn(themeName, OlyWebConfigProperties.PAGE_ABOUT));
        return getPrefix(themeName, "/pages/web/about", mp);
    }

    /**
     * 排行页面
     *
     * @param themeName
     * @param mp
     * @return
     */
    public String rank(String themeName, ModelMap mp) {
        mp.put("column", getCmsColumn(themeName, OlyWebConfigProperties.PAGE_RANK));
        return getPrefix(themeName, "/pages/web/rank", mp);
    }

    /**
     * 时间线页面
     *
     * @param themeName
     * @param mp
     * @return
     */
    public String timeLine(String themeName, ModelMap mp) {
        mp.put("column", getCmsColumn(themeName,
                OlyWebConfigProperties.PAGE_TIMELINE));
        return getPrefix(themeName, "/pages/web/timeLine", mp);
    }

    /**
     * 反馈页面
     *
     * @param themeName
     * @param mp
     * @return
     */
    public String contact(String themeName, ModelMap mp) {
        mp.put("column", getCmsColumn(themeName,
                OlyWebConfigProperties.PAGE_INTRODUCE));
        return getPrefix(themeName, "/pages/web/contact", mp);
    }

    /**
     * 联盟页面
     *
     * @param themeName
     * @param mp
     * @return
     */
    public String union(String themeName, ModelMap mp) {
        mp.put("column", getCmsColumn(themeName, OlyWebConfigProperties.PAGE_UNION));
        return getPrefix(themeName, "/pages/web/union", mp);
    }

    /**
     * 自定义页面
     *
     * @param themeName
     * @param mp
     * @param page
     * @return
     */
    public String custom(String themeName, ModelMap mp, String page) {
        return getPrefix(themeName, "/pages/custom/" + page, mp);
    }

    public void robots(String themeName, HttpServletResponse response, ModelMap mp) {
        File file = Paths
                .get(GraceServerRoot.THEME_DIR.getWorkRoot(themeName),GraceServerRoot.THEME_TEMPLATE_DIR.getValue(),
                        "robots.txt")
                .toFile();
        outPrint(file, response, mp);
    }

    /**
     * 索引文件列表
     *
     * @param themeName
     * @param response
     * @param mp
     */
    public void siteMapIndex(String themeName, HttpServletResponse response,
            ModelMap mp) {
        File file = Paths.get(GraceServerRoot.THEME_DIR.getWorkRoot(themeName),GraceServerRoot.THEME_TEMPLATE_DIR.getValue()
                , GraceServerRoot.SITE_DIR.getValue(), themeName +
                        "_sitemap.xml")
                .toFile();
        outPrint(file, response, mp);
    }

    /**
     * 索引文件
     *
     * @param themeName
     * @param fileName
     * @param response
     * @param mp
     */
    public void siteMap(String themeName, String fileName, HttpServletResponse response, ModelMap mp) {
        File file = Paths.get(GraceServerRoot.THEME_DIR.getWorkRoot(themeName),
            GraceServerRoot.THEME_TEMPLATE_DIR.getValue(), GraceServerRoot.SITE_DIR.getValue(),
                fileName).toFile();
        outPrint(file, response, mp);
    }

    private void outPrint(File file, HttpServletResponse response, ModelMap mp) {
        BufferedReader reader = null;
        if (!file.exists()) {
            try {
                response.getWriter().println();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        } else {
            try {
                StringBuffer sbf = new StringBuffer();
                reader = new BufferedReader(new FileReader(file));
                String tempStr;
                while ((tempStr = reader.readLine()) != null) {
                    sbf.append(tempStr).append("\n");
                }
                reader.close();
                response.getWriter().println(sbf.toString());
            } catch (IOException e) {
                log.error(e.getMessage());
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e1) {
                        log.error(e1.getMessage());
                    }
                }
            }
        }
    }

    

}
